import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

class AnimatedBar extends StatefulWidget {
  final double width;
  final double maxHeight;
  final Color color;

  const AnimatedBar({
    super.key,
    required this.width,
    required this.maxHeight,
    required this.color,
  });

  @override
  State<AnimatedBar> createState() => _AnimatedBarState();
}

class _AnimatedBarState extends State<AnimatedBar>
    with SingleTickerProviderStateMixin {
  late double height;
  final Random _random = Random();
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    height = widget.maxHeight * _random.nextDouble();
    _startRandomAnimation();
  }

  void _startRandomAnimation() {
    _timer = Timer.periodic(
      Duration(milliseconds: 300 + _random.nextInt(300)), // 300~600ms
      (_) {
        if (!mounted) return;
        setState(() {
          height =
              widget.maxHeight * (0.1 + _random.nextDouble() * 0.7); // 30%~100%
        });
      },
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 250),
      curve: Curves.easeInOut,
      width: widget.width,
      height: height,
      decoration: BoxDecoration(
        color: widget.color,
        borderRadius: BorderRadius.circular(2),
      ),
    );
  }
}
